package by.parfen.game.service.impl;

import java.io.StringReader;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.stream.JsonParsingException;

import by.parfen.game.datamodel.GameMessage;
import by.parfen.game.datamodel.enums.MessageHeader;
import by.parfen.game.service.GameMessageService;

public class GameMessageServiceImpl implements GameMessageService {

	private static final String MESSAGE_DELIMITER = "|";
	private static final String MESSAGE_TEXT_DELIMITER = ";";

	// TODO
	// use MessageHeader: LOGIN, INVITE, ACCEPT, GAME, MOVE, FINISH

	@Override
	public String convertMessage2String(GameMessage message) {
		String result = "";
		if (message != null) {
			result = message.getSubject() + MESSAGE_DELIMITER + message.getContent();
		}
		return result;
	}

	@Override
	public GameMessage convertString2Message(String text) {
		GameMessage message = new GameMessage();
		if (text != null) {
			String[] values = text.split(MESSAGE_DELIMITER, 2);
			if (values.length == 2) {
				message.setSubject(values[0]);
				message.setContent(values[1]);
			}
		}
		return message;
	}

	@Override
	public GameMessage createLoginMessage(String player) {
		GameMessage message = new GameMessage();
		message.setSubject(MessageHeader.LOGIN.name());
		message.setContent(player);
		return message;
	}

	@Override
	public GameMessage createInviteMessage(String inviter, String player) {
		GameMessage message = new GameMessage();
		message.setSubject(MessageHeader.INVITE.name());
		message.setContent(inviter + MESSAGE_TEXT_DELIMITER + player);
		return message;
	}

	@Override
	public JsonObject encode(GameMessage message) {
		JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
		jsonBuilder.add("subject", message.getSubject());
		jsonBuilder.add("content", message.getContent());
		JsonObject jsonObject = jsonBuilder.build();
		return jsonObject;
	}

	@Override
	public GameMessage decode(String jsonStringMessage) {
		GameMessage message = new GameMessage();
		try {
			JsonObject jsonObject = Json.createReader(new StringReader(jsonStringMessage)).readObject();
			message.setSubject(jsonObject.getString("subject"));
			message.setContent(jsonObject.getString("content"));
		} catch (JsonParsingException e) {
			// e.printStackTrace();
		}
		return message;
	}

}
